package com.heng.controller;

import com.heng.dao.entity.ShippingAddress;
import com.heng.service.ShippingAddressService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/addresses")
public class ShippingAddressController {

    @Resource
    private ShippingAddressService shippingAddressService;

    /**
     * 查询用户所有地址
     */
    @GetMapping
    public Map<String, Object> listAddresses(@RequestHeader("Authorization") String token) {
        Long userId = 1001L; // 实际从Token解析
        List<ShippingAddress> addressList = shippingAddressService.listByUserId(userId);
        
        return Map.of(
            "code", 200,
            "msg", "查询成功",
            "data", addressList
        );
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/{id}/default")
    public Map<String, Object> setDefault(@PathVariable Long id, @RequestHeader("Authorization") String token) {
        Long userId = 1001L; // 实际从Token解析
        
        // 1. 先取消当前默认地址
        ShippingAddress defaultAddress = shippingAddressService.getDefaultByUserId(userId);
        if (defaultAddress != null) {
            defaultAddress.setIsDefault(0);
            shippingAddressService.updateById(defaultAddress);
        }
        
        // 2. 设置目标地址为默认
        ShippingAddress targetAddress = shippingAddressService.getById(id);
        if (targetAddress == null || !targetAddress.getUserId().equals(userId)) {
            return Map.of("code", 400, "msg", "地址不存在或无权操作");
        }
        targetAddress.setIsDefault(1);
        shippingAddressService.updateById(targetAddress);
        
        return Map.of("code", 200, "msg", "默认地址设置成功");
    }
}